/*
 * Worker.cpp
 *
 *  Created on: 31-07-2011
 *      Author: cristian
 */

#include "Worker.h"

Worker::Worker(std::string _nombre, std::string _descripcion) {

	setNombre(_nombre);
	setDescripcion(_descripcion);
	this->setRun(1);
	this->logger = new Logger();
	this->database = Database::getInstance();
	this->thread = new pthread_t;
	this->attr = new pthread_attr_t;
	pthread_attr_init(attr);
	pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);

}

std::string Worker::getDescripcion() const {
	return descripcion;
}

std::string Worker::getNombre() const {
	return nombre;
}

void Worker::setDescripcion(std::string descripcion) {
	this->descripcion = descripcion;
}

void Worker::setNombre(std::string nombre) {
	this->nombre = nombre;
}

Worker::~Worker() {

	delete this->database;
	delete this->logger;
}

void Worker::trace() {
#ifdef TRACE
	HAL_TRACE(this->logger, "nombre %s", this->getNombre().c_str());
	HAL_TRACE(this->logger, "descripcion %s", this->getDescripcion().c_str());
	HAL_TRACE(this->logger, "Pthread  %u", *thread);

//	this->database->printAll();
#endif
}

int Worker::getRun() const {
	return run;
}

void Worker::setRun(int run) {
	this->run = run;
}

void *Worker::work(void *arg) {

	srand (time(NULL) );while(this->getRun()) {
		sleep(rand() % 4 + 1);
		//this->trace();
		//this->updateObservers();
	}
#ifdef TRACE
	HAL_TRACE(this->logger, "worker %s , stop",this->getNombre().c_str() );
#endif

}

void *Worker::start(void *arg) {
	((Worker*) arg)->work(arg);
}

void Worker::stop() {
	this->setRun(0);
}

void Worker::addObserver(Observer *observer) {
	this->observers.push_back(observer);
}

void Worker::updateObservers() {
	list<Observer*>::iterator pos;
	pos = this->observers.begin();

	while (pos != this->observers.end()) {
		((*pos))->update();
		pos++;
	}
}

pthread_t* Worker::getThread() const
{
    return thread;
}


pthread_attr_t *Worker::getAttr() const
{
    return attr;
}

void Worker::setAttr(pthread_attr_t *attr)
{
    this->attr = attr;
}

void Worker::update()
{
#ifdef TRACE
	HAL_TRACE(logger, "worker %s updateado " , this->nombre.c_str());
#endif
}



